import { EggAppConfig, PowerPartial } from 'egg'

// for config.{env}.ts
export type DefaultConfig = PowerPartial<EggAppConfig & BizConfig>

// app special config scheme
export interface BizConfig {
  sampleOptions: any
  globalOptions: any
  settings: any
}

export default (appInfo: EggAppConfig) => {
  const config: PowerPartial<EggAppConfig> & BizConfig = {
    sampleOptions: { test: 'sample.' },
    globalOptions: null,
    settings: null,
  }

  // app special config
  config.sourceUrl = `https://github.com/eggjs/examples/tree/master/${appInfo.name}`

  // override config from framework / plugin
  // use for cookie sign key, should change to your own and keep security
  config.keys = appInfo.name + '_1527065727941_1991'

  config.security = {
    csrf: {
      useSession: true,
      // 忽略本机调用的 CSRF 防范
      ignore: ctx => ['::1', '127.0.0.1', 'localhost'].indexOf(ctx.ip) >= 0,
    },
  }
  config.bodyParser = {
    jsonLimit: '10mb',
    formLimit: '10mb',
  }
  config.cors = { origin: '*', credentials: true }
  config.multipart = {
    fileSize: '10mb',
    fileExtensions: ['.apk', '.pdf', '.exe', ''],
  }

  // add your config here
  config.middleware = ['compress', 'global', 'jwt', 'sample']
  config.compress = { threshold: 2048 }
  config.jwt = {
    enable: true,
    ignore: ctx => {
      const { url } = ctx
      return (ctx.app.config.settings.jwtIgnorePaths || [])
        .some(ignorePath => url === ignorePath ||
          url.startsWith(`${ignorePath}/`) || url.startsWith(`${ignorePath}?`))
    },
    secret: config.keys,
    passthrough: false,
    key: 'user',
    // tokenKey: 'token',
  }
  config.io = {
    // passed to engine.io
    init: {
      // default: us
      wsEngine: 'us',
      // wsEngine: 'uws',
    },
    namespace: {
      '/': {
        connectionMiddleware: ['auth', 'connection'],
        packetMiddleware: ['auth', 'packet'],
      },
      // '/res': {
      //   connectionMiddleware: ['connection'],
      //   packetMiddleware: ['packet'],
      // },
    },
  }
  config.sample = { enable: true, match: '/sample' }

  config.sequelize = {
    dialect: 'postgres',
    database: 'egg-ts',
    host: '192.168.1.21',
    port: '5432',
    username: 'postgres',
    password: 'it9s2cu',
    logging: false,
    omitNull: false,
    native: false,
    dialectOptions: { ssl: false },
    timezone: '+08:00',
    define: {
      underscored: false,
      freezeTableName: true,
      charset: 'utf8',
      dialectOptions: { collate: 'utf8_general_ci' },
      timestamps: true,
      paranoid: true,
      version: true,
    },
  }

  config.settings = {
    dbSyncForce: false,
    dbSeedData: true,
    jwtSecret: config.keys,
    jwtOptions: {
      algorithm: 'HS512',
      expiresIn: '7d',
      audience: 'http://frozen.com',
      issuer: 'http://frozen-server.frozen.com',
      subject: 'frozen',
      jwtid: 'jti',
    },
    jwtIgnorePaths: ['/', '/login', '/public', '/sample'],
    apiRouterPath: '/api/',
    entityRouterPath: '/entity/',
    querySettings: {
      offset: 0,
      limit: 10,
      order: [['createdAt', 'DESC']],
      max: 99999,
    },
    dataPath: `${appInfo.baseDir}/data`,
    uploadPath: `${appInfo.baseDir}/app/public/upload`,
    // double或者float数值乘以这个值后round，再除以这个值
    defaultRoundPrecision: 1000,
    // 金额数值乘以这个值后round，再除以这个值
    moneyRoundPrecision: 1000,
  }

  return config
}
